package com.shenganyuan.smac.check;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.amap.api.maps2d.model.LatLng;
import com.oklib.utils.Logger.Logger;
import com.oklib.utils.helper.RxUtil;
import com.oklib.utils.network.http.ViseHttp;
import com.oklib.utils.network.http.callback.ACallback;
import com.oklib.utils.network.http.subscriber.ApiCallbackSubscriber;
import com.oklib.utils.network.loader.ILoader;
import com.oklib.utils.network.loader.LoaderManager;
import com.oklib.utils.view.SnackbarUtil;
import com.oklib.widget.recyclerview.BaseQuickAdapter;
import com.oklib.widget.recyclerview.BaseViewHolder;
import com.oklib.widget.recyclerview.CoreRecyclerView;
import com.oklib.widget.recyclerview.listener.OnItemChildClickListener;
import com.oklib.widget.recyclerview.listener.OnItemClickListener;
import com.shenganyuan.smac.App;
import com.shenganyuan.smac.R;
import com.shenganyuan.smac.common.BaseActivity;
import com.shenganyuan.smac.common.Config;
import com.shenganyuan.smac.common.beans.ApiCheckRecords;
import com.shenganyuan.smac.common.beans.ApiRiskPoints;
import com.shenganyuan.smac.common.beans.BeanCheckRecord;
import com.shenganyuan.smac.common.beans.EventRefreshPage;
import com.shenganyuan.smac.common.beans.RiskPoint;
import com.shenganyuan.smac.common.beans.User;
import com.shenganyuan.smac.common.data.Api;
import com.shenganyuan.smac.common.utils.DataConverter;
import com.shenganyuan.smac.common.view.CommonBottomListDialog;
import com.shenganyuan.smac.common.view.RecyclerViewItemDivider;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 巡查记录
 *
 * @author Damon
 */

public class ActCheckRecords extends BaseActivity {
    @BindView(R.id.work_check_record_recycler)
    CoreRecyclerView recycler;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.txt_check_position)
    TextView txt_check_position;
    @BindView(R.id.container_check_position)
    View container_check_position;
    //巡查位置集合
    List<RiskPoint> points = new ArrayList<>();
    private RiskPoint currentPoint;

    @Override
    public int getLayoutId() {
        return R.layout.act_check_records;
    }

    @Override
    public void initUI(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        recycler.init(new BaseQuickAdapter<BeanCheckRecord, BaseViewHolder>(R.layout.act_check_record_item) {
            @Override
            protected void convert(BaseViewHolder helper, BeanCheckRecord item) {
                helper.setText(R.id.tv_position, item.getGkZydyName()).addOnClickListener(R.id.tv_position);
                helper.setText(R.id.tv_desc, item.getXcjl());
                helper.setText(R.id.tv_zq, item.getZq());
                helper.setText(R.id.tv_time, DataConverter.getDateStr(item.getLrTime()));
                String imgStrs = item.getXczp();
                if (imgStrs != null) {
                    String imgUrl = "";
                    if (imgStrs.contains(";")) {
                        String urls[] = imgStrs.split(";");
                        imgUrl = urls[0];
                    } else {
                        imgUrl = imgStrs;
                    }
                    LoaderManager.getLoader().loadNet(helper.getView(R.id.img), imgUrl, new ILoader.Options(R.drawable.lib_img_default, R.drawable.lib_img_default));
                }
            }
        });
        recycler.getRecyclerView().addItemDecoration(new RecyclerViewItemDivider(mContext, LinearLayoutManager.VERTICAL)
                .setAppearance(20, "#ffe2e2e2"));
        recycler.addOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                Logger.e("item 点击");
            }
        });
        recycler.addOnChildItemClickListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_position:
                        BeanCheckRecord item = (BeanCheckRecord) adapter.getItem(position);
                        String gps = item.getGps();
                        LatLng latLng = DataConverter.fromStrToLatLng(gps);
                        if (latLng == null) {
                            SnackbarUtil.show(getWindow().getDecorView(), "不可用的定位数据");
                            return;
                        }
                        DataConverter.openSdkMap(mContext, latLng.latitude, latLng.longitude);
                        break;
                }
            }
        });
        recycler.openRefresh(new CoreRecyclerView.addDataListener() {
            @Override
            public void addData(int page) {
                getServerData(currentPoint);
            }
        });
    }


    @Override
    public void initData() {
        setTitle("巡查记录");
        getRiskPointFromServer();
        getServerData(currentPoint);
        txt_check_position.setText("全部");
    }

    private void getRiskPointFromServer() {
        User user = App.getCurrentUser();
        ViseHttp.RETROFIT().create(Api.class).getRiskPoints(user.getId(), App.getAccessToken())
                .compose(RxUtil.rxSchedulerHelper()).subscribe(new ApiCallbackSubscriber<>(new ACallback<ApiRiskPoints>() {
            @Override
            public void onSuccess(ApiRiskPoints data) {
                try {
                    if ("true".equalsIgnoreCase(data.getResult())) {
                        points.clear();
                        points.addAll(data.getGkzydy());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                SnackbarUtil.showShort(getWindow().getDecorView(), "获取巡查点信息失败");
            }
        }));
    }

    /**
     * 获取信息
     *
     * @param riskPoint
     */
    private void getServerData(RiskPoint riskPoint) {
        String pointId = null;
        if (riskPoint != null) {
            pointId = riskPoint.getId();
        }
        User user = App.getCurrentUser();
        ViseHttp.RETROFIT().create(Api.class).getCheckRecords(user.getId(), pointId, App.getAccessToken())
                .compose(RxUtil.rxSchedulerHelper()).subscribe(new ApiCallbackSubscriber<>(new ACallback<ApiCheckRecords>() {
            @Override
            public void onSuccess(ApiCheckRecords data) {
                try {
                    if ("true".equalsIgnoreCase(data.getResult())) {
                        recycler.getAdapter().setNewData(data.getPcxcxx());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                SnackbarUtil.showShort(getWindow().getDecorView(), "获取巡查记录信息失败");
            }
        }));
    }

    @OnClick({R.id.container_check_position})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.container_check_position:
                pickPosition();
                break;
        }
    }

    /**
     * 选择巡查点
     */
    public CommonBottomListDialog pickPosition() {
        ArrayList<String> datas = new ArrayList<>();
        for (int i = 0; i < points.size(); i++) {
            if (TextUtils.isEmpty(points.get(i).getId())) {
                datas.add("全部");
            } else {
                datas.add(points.get(i).getName());
            }
        }

        CommonBottomListDialog commonBottomListDialog = CommonBottomListDialog.newInstance(datas);
        commonBottomListDialog.setTitle(

                getString(R.string.tilte_choose_position));
        commonBottomListDialog.setDefaultCheckValue(txt_check_position.getText().

                toString());
        commonBottomListDialog.addOnSingleCheckListener(new CommonBottomListDialog.OnSingleCheckListener() {
            @Override
            public void onSingleCheck(int position, String value) {
                currentPoint = points.get(position);
                txt_check_position.setText(value);
                getServerData(currentPoint);
            }
        });
        commonBottomListDialog.show(

                getSupportFragmentManager(), "check_position");
        return commonBottomListDialog;
    }

    @Subscribe
    public void onEventRefreshPage(EventRefreshPage iEvent) {
        if (iEvent != null ) {
            if (iEvent.type == Config.EventKit.KEY_EVENT_REFRESH_ACTCHECKRECORDS) {
                refreshPage();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 刷新页面数据
     */
    private void refreshPage() {
        getServerData(currentPoint);
    }
}
